﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BugNET.UserInterfaceLayer;
using BugNET.BLL;
using BugNET.Common;
using BugNET.Entities;
using System.Text;
using System.Text.RegularExpressions;

namespace BugNET.WikiPages
{
    public partial class ShowWiki : BasePage
    {

        Project CurrentProject;

        bool CanEditWiki;

        /// <summary>
        /// Gets or sets the project id.
        /// </summary>
        /// <value>The project id.</value>
        public override int ProjectId
        {
            get { return Convert.ToInt16(Session["ProjectId"]); }
            set { Session["ProjectId"] = value; }
        }

        /// <summary>
        /// Gets or sets the wikiId
        /// </summary>
        /// <value>The wikiId.</value>
        int wikiId
        {
            get { return Convert.ToInt16(Session["wikiId"]); }
            set { Session["wikiId"] = value; }
        }

        /// <summary>
        /// Gets or sets the wikiPageId
        /// </summary>
        /// <value>The wikiPageId.</value>
        int wikiPageId
        {
            get { return Convert.ToInt16(Session["wikiPageId"]); }
            set { Session["wikiPageId"] = value; }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!UserManager.HasPermission(ProjectId, Common.Permission.ViewWiki.ToString()))
                Response.Redirect("~/Errors/AccessDenied.aspx");

            // WikiPageId = Request.QueryString.Get("wikiPageId", 0);

            if (!IsPostBack)
            {
                // If don't know project or issue then redirect to something missing page
                if (ProjectId == 0)
                    ErrorRedirector.TransferToSomethingMissingPage(Page);

                CurrentProject = ProjectManager.GetById(ProjectId);

                if (CurrentProject == null)
                {
                    ErrorRedirector.TransferToNotFoundPage(Page);
                    return;
                }

                //security check: add issue
                if (!UserManager.HasPermission(ProjectId, Common.Permission.ViewWiki.ToString()))
                {
                    ErrorRedirector.TransferToLoginPage(Page);
                }

                Page.Title = GetLocalResourceObject("PageTitle").ToString();

                // The ExpandIssuePaths method is called to handle
                // the SiteMapResolve event.
                SiteMap.SiteMapResolve += ExpandWikiPagePaths;

                CanEditWiki = UserManager.HasPermission(ProjectId, Common.Permission.EditWiki.ToString());

                editorPanel.Visible = pnlWikiActionButtons.Visible = CanEditWiki;
                divReadonlyContent.Visible = !CanEditWiki;

                GetWikiContent(ProjectId, wikiPageId);

            }


        }

        private void GetWikiContent(int projectId, int wikiPageId)
        {
            string wikiPageName = string.Empty;
            List<Wiki> wikiList = WikiManager.GetWikiContent(projectId, wikiPageId, ref wikiPageName);
            divWikiPageName.InnerText = "Page Name: " + wikiPageName;
            BindWikiHistory(wikiList);

            if (wikiList.Count <= 0)
                return;
            if (CanEditWiki && (wikiId == 0 || wikiList[0].WikiId == wikiId))
            {
                editorPanel.Visible = pnlWikiActionButtons.Visible = true;
                divReadonlyContent.Visible = false;
                txtWikiContents.Text = System.Web.HttpUtility.HtmlDecode(wikiList[0].WikiHTML);
            }
            else
            {
                editorPanel.Visible = pnlWikiActionButtons.Visible = false;
                divReadonlyContent.Visible = true;
                if (wikiId == 0)
                    divReadonlyContent.InnerHtml = System.Web.HttpUtility.HtmlDecode(wikiList[0].WikiHTML);
                else
                    divReadonlyContent.InnerHtml = wikiList.Where(o => o.WikiId == wikiId).SingleOrDefault().WikiHTML;
            }


        }

        /// <summary>
        /// Handles the Click event of the lnkDone control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LnkDoneClick(object sender, EventArgs e)
        {
            SaveWikiContent();
            Response.Redirect("ShowWikiPageList.aspx?pid=" + ProjectId);
        }

        /// <summary>
        /// Cancels the button click.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CancelButtonClick(Object s, EventArgs e)
        {
            Response.Redirect("ShowWikiPageList.aspx?pid=" + ProjectId);
        }

        /// <summary>
        /// Handles the Click event of the lnkSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void LnkSaveClick(object sender, EventArgs e)
        {
            SaveWikiContent();
        }

        public void SaveWikiContent()
        {
            string htmlContent = System.Web.HttpUtility.HtmlDecode(txtWikiContents.Text);
            string textContent = Regex.Replace(htmlContent, @"<(.|\n)*?>", string.Empty);
            txtWikiContents.Text = System.Web.HttpUtility.HtmlDecode(txtWikiContents.Text);
            if (string.IsNullOrEmpty(htmlContent))
                return;

            var wikiobject = new Wiki
            {
                WikiPageId = wikiPageId,
                ProjectId = ProjectId,
                WikiHTML = htmlContent,
                WikiText = textContent,
                UserCreated = Security.GetUserName(),
            };

            int resultValue = 0;
            List<Wiki> wikiHistoryList = WikiManager.SaveWikiContent(wikiobject, ref resultValue);

            if (wikiHistoryList.Count > 0)
                wikiId = wikiHistoryList[0].WikiId;

            BindWikiHistory(wikiHistoryList);

            if (resultValue == -1)
            {
                Message1.ShowErrorMessage(Resources.Exceptions.SaveWikiNothingToUpdate);
            }
            else if (resultValue == 0)
            {
                Message1.ShowErrorMessage(Resources.Exceptions.SaveWikiError);
            }
        }

        protected void HTMLEditorExtender_ImageUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            string fullpath = Server.MapPath("~/WikiPages/UserUploadedImages/") + e.FileName;
            html_editor.AjaxFileUpload.SaveAs(fullpath);
            e.PostedUrl = Page.ResolveUrl("~/WikiPages/UserUploadedImages/" + e.FileName);
        }

        public void BindWikiHistory(List<Wiki> wikiHistoryList)
        {
            grdVwWikiPagesHistory.DataSource = wikiHistoryList;
            grdVwWikiPagesHistory.DataBind();
            if (wikiHistoryList.Count > 30)
            {
                pager.Visible = true;
            }

        }

        protected void grdVwWikiPagesHistoryDetails_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var currentWikiPage = (Wiki)e.Row.DataItem;

                var lblVersionNo = (LinkButton)e.Row.FindControl("lnVersionNo");
                if (lblVersionNo != null)
                {
                    lblVersionNo.Text = "Version: " + Convert.ToString(currentWikiPage.WikiId);
                    lblVersionNo.CommandArgument = Convert.ToString(currentWikiPage.WikiId);
                    lblVersionNo.ToolTip = currentWikiPage.DateCreated.ToShortDateString();
                    if (currentWikiPage.WikiId == wikiId || (wikiId == 0 && e.Row.RowIndex == 0))
                    {
                        lblVersionNo.Style.Add("color", "#F4620B");
                    }
                }

                var lblPageCreatedBy = (Label)e.Row.FindControl("lblCreatedBy");
                if (lblPageCreatedBy != null)
                {
                    lblPageCreatedBy.Text = currentWikiPage.UserCreated;
                }
            }
        }

        protected void grdVwWikiPagesHistoryDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Navigate")
            {
                LinkButton imgBtn = (LinkButton)e.CommandSource;
                wikiId = Convert.ToInt16(e.CommandArgument);
                Response.Redirect(Request.Url.ToString());

            }

        }


        /// <summary>
        /// Handles the PageIndexChanging event of the grdVwWikiPagesHistory control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Web.UI.WebControls.GridViewPageEventArgs"/> instance containing the event data.</param>
        protected void grdVwWikiPagesHistoryDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grdVwWikiPagesHistory.PageIndex = e.NewPageIndex; // needed for server side paging
            //BindWikiPages();

        }

        /// <summary>
        /// Handles the Unload event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Unload(object sender, EventArgs e)
        {
            //remove the event handler
            SiteMap.SiteMapResolve -= ExpandWikiPagePaths;
        }

        /// <summary>
        /// Expands the issue paths.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Web.SiteMapResolveEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        private SiteMapNode ExpandWikiPagePaths(Object sender, SiteMapResolveEventArgs e)
        {
            if (SiteMap.CurrentNode == null) return null;

            var currentNode = SiteMap.CurrentNode.Clone(true);
            var tempNode = currentNode;

            // The current node, and its parents, can be modified to include
            // dynamic query string information relevant to the currently
            // executing request.

            if ((null != (tempNode = tempNode.ParentNode)))
            {
                tempNode.Url = string.Format("~/WikiPages/ShowWikiPageList.aspx?pid={0}", ProjectId);
            }

            return currentNode;
        }


    }
}